package com.hdu.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdu.entity.CourseBase;
import com.hdu.entity.CourseTeacher;
import com.hdu.exception.BizException;
import com.hdu.mapper.CourseBaseMapper;
import com.hdu.mapper.CourseTeacherMapper;
import com.hdu.service.ICourseTeacherService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
@RequiredArgsConstructor
public class CourseTeacherServiceImpl extends ServiceImpl<CourseTeacherMapper, CourseTeacher> implements ICourseTeacherService {

    private final CourseTeacherMapper courseTeacherMapper;
    private final CourseBaseMapper courseBaseMapper;

    @Override
    public CourseTeacher getCourseTeacherList(Long courseId) {
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        return courseTeacherMapper.selectById(courseBase.getTeacherId());
    }

    @Transactional
    @Override
    public CourseTeacher saveCourseTeacher(CourseTeacher courseTeacher) {
        Long id = courseTeacher.getId();
        CourseTeacher teacher;
        if (id == null) {
            // id为null，新增教师
            teacher = new CourseTeacher();
            BeanUtils.copyProperties(courseTeacher, teacher);
            teacher.setCreateDate(LocalDateTime.now());
            int flag = courseTeacherMapper.insert(teacher);
            if (flag <= 0)
                throw new BizException("新增失败");
        } else {
            // id不为null，修改教师
            teacher = courseTeacherMapper.selectById(id);
            BeanUtils.copyProperties(courseTeacher, teacher);
            int flag = courseTeacherMapper.updateById(teacher);
            if (flag <= 0)
                throw new BizException("修改失败");
        }
        return getCourseTeacher(teacher);
    }

    @Override
    public void deleteCourseTeacher(Long courseId, Long teacherId) {
        UpdateWrapper<CourseBase> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", courseId)  // 指定ID条件
                .set("teacher_id", null); // 设置要更新的字段
        int flag = courseBaseMapper.update(null, updateWrapper);
        if (flag < 0)
            throw new BizException("删除失败");
    }

    public CourseTeacher getCourseTeacher(CourseTeacher courseTeacher) {
        return courseTeacherMapper.selectById(courseTeacher.getId());
    }
}
